<template>
    <div>
        <!--当前场所选择-->.
        <el-form :model="item">
            <el-form-item :label-width="formLabelWidth" label="所属场所">
                <el-select placeholder="--请选择场所--" v-model="item.dsAreaId">
                    <el-option :key="one.dsAreaId" :label="one.dsAreaName" :value="one.dsAreaId"
                               @click.native="HuoQuZheXian" v-for="one in areasTemp">{{ one.dsAreaName }}
                    </el-option>
                </el-select>
                <span>传感器个数： {{zhexianLength}}个（MAX：3）</span>
            </el-form-item>

        </el-form>
        <div id="qqq" ref="myChart"></div>
    </div>
</template>

<script>
    import * as echarts from "echarts";

    export default {
        inject: ['reload'],  //注入依赖
        name: "EchartView",
        data() {
            return {
                zhexianLength:0,
                flag:0,
                initialData:null,
                initialDataTemp:null,
                formLabelWidth: '80px',
                connection: {
                    host: "broker.emqx.io",//链接地址
                    port: "8083",//端口
                    endpoint: "/mqtt",
                    clean: true, // 保留会话
                    connectTimeout: 4000, // 超时时间
                    reconnectPeriod: 4000, // 重连时间间隔
                    // 认证信息
                    clientId: "mqttjs_3be2c321" + new Date().getTime(),
                    username: "",//用户名 不用的话什么也不用填
                    password: "",//密码 不用的话什么也不用填
                },
                subscription: {
                    topic: "suiji",
                    qos: 0,
                },
                receiveNews: "",
                client: {
                    connected: false,
                },
                subscribeSuccess: false,
                msg: null,
                temArray: [],
                temArray2: [],
                temArray3:[],
                dateArray: [],
                temDate: null,
                item: {
                    dsAreaId: null,
                },
                tableData: [
                    this.item
                ],
                area: {
                    dsAreaId: null,
                    dsAreaName: null,
                },
                areas: [
                    this.area
                ],
                type: {
                    dsTypeId: null,
                    dsTypeName: null,
                },
                types: [
                    this.type
                ],
                areasTemp: null,
            }

        },
        methods: {
            HuoQuZheXian() {
                //初始化判断
                if (this.flag===0){
                    this.item.dsAreaId =  this.initialData
                }
                this.api.HistoryApi.HuoQuZheXian(this.item.dsAreaId).then(res => {
                    // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
                    let lengthOne = res.length
                    // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+res.toString())
                    // console.log(res.join(","))
                    // let s = res.toString().split("℃").join("")
                    // let temp = s.split(",")
                    // console.log(temp)
                    // for (let  j = 0; j < lengthOne; j++) {
                    //     for (let  i = 0; i < res[j].length; i++) {
                    //         let type =typeof JSON.parse(res[j][i])
                    //         if (type !="number") {
                    //             res[j][i] = -1
                    //         }
                    //     }
                    // }
                    this.zhexianLength=lengthOne
                    res.forEach(arr => {
                        arr.reverse()
                        }
                    )
                    this.temArray = res[0]
                    this.temArray2 = res[1]
                    this.temArray3 = res[2]  //测试数据
                    if(this.flag===0){
                        this.flag=null
                        this.item.dsAreaId =  "（默认值）"
                    }
                    this.init()
                }).catch(err => {
                    console.log(err)
                })
            },

            show(mac) {
                this.api.HistoryApi.HuoQuTEM(mac).then(res => {
                    if (res.code === "200") {
                        let arr = res.data.reverse()
                        arr.forEach(val => {
                            // this.temArray.push(val.dsHistoryValue)//返回获取温度的数组
                            this.dateArray.push(new Date(val.createTime).getHours() + ":" + new Date(val.createTime).getMinutes())
                        })
                        this.temDate = new Date(arr[arr.length - 1].createTime).toLocaleDateString()
                        this.init()
                    } else {
                        this.$message.error(res.meg);
                    }
                })
            },
            //初始化画图
            init() {
                //获取到容器
                let myEchatrs = echarts.init(this.$refs.myChart)
                //设置数据
                let option = {

                    title: { //设置就是标题
                        text: "室内温度  " + this.temDate,
                        textStyle: {
                            color: "black",
                        }
                    },
                    tooltip: {
                        //触发类型
                        trigger: 'axis',//item图形触发
                        //坐标轴指示器
                        axisPointer: {
                            type: 'cross'//line 默认 显示一根实线 shadow 阴影效果  cross十字准星
                        },
                        //悬浮层 样式
                        textStyle: {
                            color: 'black'
                        },
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            dataView: {readOnly: false},
                            magicType: {type: ['line', 'bar']},
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    //设置X轴参数
                    xAxis: {
                        type: 'category',
                        data: this.dateArray
                    },
                    //设置Y轴参数
                    yAxis: {
                        type: 'value',
                        scale: true,//使得y轴缩放，自动改变y轴起始值
                        axisLabel: {
                            formatter: '{value} °C'
                        }
                    },
                    series: [
                        //折线数据01
                        {
                            data: this.temArray,
                            type: 'line',
                            smooth: true,//开启平滑度
                            markPoint: {
                                data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
                            },
                            markLine: {
                                data: [{type: 'average', name: '平均值'}]
                            }
                        },
                        //折线数据02
                        {
                            data: this.temArray2,
                            type: "line",
                            smooth: true,//开启平滑度
                            markPoint: {
                                data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
                            },
                            markLine: {
                                data: [{type: 'average', name: '平均值'}]
                            }
                        },
                        //折线数据03
                        {
                            data: this.temArray3,
                            type: "line",
                            smooth: true,//开启平滑度
                            markPoint: {
                                data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
                            },
                            markLine: {
                                data: [{type: 'average', name: '平均值'}]
                            }
                        }
                    ]
                };
                //设置配置项 就是将数据装入其中。
                myEchatrs.setOption(option)
            },
        },
        mounted() {
            this.show('esp8266_F687C9')
            this.api.areaApi.selectAreas()
                .then(res => {
                    this.areas = res
                    this.areasTemp = this.areas
                })
                .catch(error => {
                    console.log(error)
                })

            this.api.typeApi.selectTypes()
                .then(res => {
                    this.types = res
                })
                .catch(err => {
                    console.log(err)
                })
            this.HuoQuZheXian()
            this.api.deviceApi.selectAreaIDByDeviceTypeID("2")//2为设备类型ID，代表温度传感器的值
            .then(res=>{
                this.initialData=res[0]
                this.HuoQuZheXian()
            })
            .catch(err=>{
                console.log(err)
            })



        },

    }

</script>

<style scoped>
    #qqq {
        width: auto;
        height: 400px;
        background-color: white;
    }
</style>